package com.voute.View.Fragement;

import android.graphics.Color;
import android.support.design.widget.Snackbar;
import android.support.v4.widget.SwipeRefreshLayout;
import android.text.TextUtils;
import android.widget.AbsListView;
import android.widget.ListView;

import com.afollestad.materialdialogs.MaterialDialog;
import com.voute.Base.BaseFragment;
import com.voute.Model.Action.ActionSearchWords;
import com.voute.Model.Bean.HotWordsBean;
import com.voute.Model.Bean.SearchResultBean;
import com.voute.Model.Bean.SearchResultEntity;
import com.voute.Presenter.ISearchPresenter;
import com.voute.Presenter.Impl.SearchPresenterImpl;
import com.voute.R;
import com.voute.Utils.RxBus;
import com.voute.View.Adapter.SearchResultAdapter;
import com.voute.View.IView.ISearchView;

import java.util.ArrayList;
import java.util.HashMap;

import rx.Subscription;
import rx.functions.Action1;

/**
 * 搜索结果Fragment展示页面
 * Created by liucxu on 2017/1/14.
 */

public class SearchResultFragment extends BaseFragment implements ISearchView {

    private SearchResultAdapter adapter;
    private SwipeRefreshLayout swipe_refresh;
    private ISearchPresenter prensenter;
    private ArrayList<SearchResultEntity> datas = new ArrayList<>();
    private ListView content_list;
    private boolean stopLoadMore;
    private boolean isLoading;
    private int page = 1;
    private String query_words = "";
    private boolean isRefresh = true;
    Subscription rxSubscription;

    @Override
    public int getLayoutId() {
        return R.layout.fragment_search_result;
    }

    @Override
    public void setupView() {
        query_words = getArguments().getString("query_words", "");
        swipe_refresh = $(R.id.swipe_refresh);
        swipe_refresh.setColorSchemeColors(Color.parseColor("#0f88eb"));
        adapter = new SearchResultAdapter(getActivity(), datas);
        content_list = $(R.id.content_list);
        content_list.setAdapter(adapter);
        prensenter = new SearchPresenterImpl(this);
        swipe_refresh.setOnRefreshListener(new SwipeRefreshLayout.OnRefreshListener() {
            @Override
            public void onRefresh() {
                isRefresh = true;
                getPageQueryResults(isRefresh);
            }
        });

        content_list.setOnScrollListener(new AbsListView.OnScrollListener() {
            @Override
            public void onScrollStateChanged(AbsListView absListView, int i) {

            }

            @Override
            public void onScroll(AbsListView absListView, int firstVisibleItem, int visibleItemCount, int totalItemCount) {
                int last_visiable = absListView.getLastVisiblePosition();
                if (!stopLoadMore && !isLoading && (last_visiable > 0)) {
                    if (last_visiable + 2 > totalItemCount) {
                        isRefresh = false;
                        getPageQueryResults(isRefresh);
                    }
                }
            }
        });

        rxSubscription= RxBus.getDefault().toObservable(ActionSearchWords.class)
                .subscribe(new Action1<ActionSearchWords>() {
                               @Override
                               public void call(ActionSearchWords action) {
                                   setNewQueryWords(action.getSearchWords());
                               }
                           },
                        new Action1<Throwable>() {
                            @Override
                            public void call(Throwable throwable) {
                            }
                        });
    }

    @Override
    public void setupData() {
        isRefresh = true;
        getPageQueryResults(true);
    }

    @Override
    public void setHotWords(HotWordsBean hot_wrod_bean) {

    }

    @Override
    public void setSearchResults(SearchResultBean search_result) {
        if (search_result != null) {
            if (search_result.getStatus() == 0) {
                isLoading = false;
                if (isRefresh) {
                    page = 1;
                    datas.clear();
                    isRefresh = false;
                }
                page = page + 1;
                datas.addAll(search_result.getData().getRecord());
                adapter.setDatas(datas);
                if (datas.size() > 0) {
                    stopLoadMore = false;
                } else {
                    stopLoadMore = true;
                    Snackbar.make(swipe_refresh,"没有更多数据了哦",Snackbar.LENGTH_SHORT).show();
                }
            } else {
                isLoading = false;
                stopLoadMore = false;
            }
        } else {
            isLoading = false;
            stopLoadMore = false;
        }
    }

    @Override
    public void setRecommandSearch(SearchResultBean recommand) {

    }

    @Override
    public void showLoading() {
        if (isRefresh) {
            swipe_refresh.setRefreshing(true);
        }
    }

    @Override
    public void hideLoading() {
        swipe_refresh.setRefreshing(false);
    }

    @Override
    public void showError(String errMsg) {
//        Snackbar.make(swipe_refresh, errMsg, Snackbar.LENGTH_SHORT).show();
        MaterialDialog notice_dialog = new MaterialDialog.Builder(getActivity()).title("提示").positiveText("确认").cancelable(false).content(errMsg).build();
        notice_dialog.show();
    }

    private void getPageQueryResults(boolean refresh){
        int current_page = 1;
        if (refresh)
            current_page = 1;
        else
            current_page = page;
        if (!refresh) {
            if (stopLoadMore) {
                return;
            } else {
                stopLoadMore = true;
                isLoading = true;
            }
        } else {
            isLoading = true;
            stopLoadMore = true;
        }
        HashMap<String, String> values = new HashMap<>();
        values.put("page", "" + current_page);
        values.put("q", query_words);
        prensenter.getSearchResults(values);
    }

    private void setNewQueryWords(String words) {
        if (!TextUtils.isEmpty(words)) {
            query_words = words;
            isRefresh=true;
            getPageQueryResults(isRefresh);
        }
    }

    @Override
    public void onDestroy() {
        super.onDestroy();
        if(!rxSubscription.isUnsubscribed()) {
            rxSubscription.unsubscribe();
        }
    }
}
